<template>
	<view class="blood-record-container">
		<view class="header">
			<view class="title">血糖详细记录</view>
			<button class="add-btn" @tap="addRecord">添加记录</button>
		</view>

		<!-- 筛选区域 -->
		<view class="filter-section">
			<view class="date-filter">
				<view 
					class="filter-item" 
					v-for="(item, index) in dateRanges" 
					:key="index"
					:class="{ active: currentDateRange === item.value }"
					@tap="changeDateRange(item.value)"
				>
					{{ item.label }}
				</view>
			</view>
			
			<view class="type-filter">
				<picker 
					mode="selector" 
					:range="typeOptions" 
					range-key="label"
					:value="typeIndex"
					@change="typeChange"
				>
					<view class="type-selector">
						<text>{{ typeOptions[typeIndex].label }}</text>
						<text class="arrow-down">▼</text>
					</view>
				</picker>
			</view>
		</view>
		
		<!-- 统计卡片 -->
		<view class="stats-card">
			<view class="stats-item">
				<text class="stats-value" :class="getValueClass(statistics.average)">{{ statistics.average }}</text>
				<text class="stats-label">平均值 (mmol/L)</text>
			</view>
			<view class="stats-item">
				<text class="stats-value" :class="getValueClass(statistics.max)">{{ statistics.max }}</text>
				<text class="stats-label">最高值 (mmol/L)</text>
			</view>
			<view class="stats-item">
				<text class="stats-value" :class="getValueClass(statistics.min)">{{ statistics.min }}</text>
				<text class="stats-label">最低值 (mmol/L)</text>
			</view>
			<view class="stats-item">
				<text class="stats-value">{{ statistics.count }}</text>
				<text class="stats-label">记录数</text>
			</view>
		</view>

		<!-- 记录列表 -->
		<view class="record-list">
			<view class="list-header">
				<text class="list-title">记录列表 ({{ filteredRecords.length }})</text>
				<view class="sort-btn" @tap="toggleSortOrder">
					<text>{{ sortDesc ? '最新优先' : '最早优先' }}</text>
					<text class="sort-icon">{{ sortDesc ? '↓' : '↑' }}</text>
				</view>
			</view>
			
			<view class="empty-tip" v-if="filteredRecords.length === 0">
				暂无符合条件的记录，请尝试调整筛选条件或添加新记录
			</view>
			
			<view class="record-group" v-for="(group, groupIndex) in recordGroups" :key="groupIndex">
				<view class="group-date">{{ formatDate(group.date) }}</view>
				
				<view class="record-item" v-for="(item, itemIndex) in group.records" :key="item.id" @tap="viewRecord(item)" @longpress="showActions(item)">
					<view class="record-time-type">
						<text class="time">{{ item.time }}</text>
						<text class="type-label">{{ getTimeTypeText(item.type) }}</text>
					</view>
					<view class="record-value-container">
						<text class="value" :class="getValueClass(item.value)">{{ item.value }}</text>
						<text class="unit">mmol/L</text>
					</view>
					<view class="record-status" :class="getStatusClass(item.value)">
						{{ getStatusText(item.value) }}
					</view>
				</view>
			</view>
		</view>
		
		<!-- 提醒卡片 -->
		<view class="reminder-card">
			<view class="card-header">
				<text class="card-title">血糖检测提醒</text>
				<text class="view-all" @tap="goToReminders">管理提醒</text>
			</view>
			
			<view class="reminder-list">
				<view class="empty-tip" v-if="bloodSugarReminders.length === 0">
					暂无血糖检测提醒，点击"管理提醒"设置
				</view>
				
				<view class="reminder-item" v-for="(item, index) in bloodSugarReminders" :key="item.id">
					<view class="reminder-info">
						<text class="reminder-title">{{ item.title }}</text>
						<text class="reminder-desc">{{ item.desc }}</text>
					</view>
					<view class="reminder-time">{{ item.time }}</view>
					<switch :checked="item.active" @change="toggleReminder(item.id, $event)" color="#8cc9a1" />
				</view>
			</view>
			
			<button class="add-reminder-btn" @tap="addReminder">添加检测提醒</button>
		</view>
	</view>
</template>

<script setup>
	import { ref, computed, reactive, onMounted } from 'vue'
	import { onShow } from '@dcloudio/uni-app'
	import { getRecords, getStatistics, deleteRecord } from '@/common/api/record.js'
	import { getReminders, toggleReminderStatus } from '@/common/api/reminder.js'
	import { formatDateFriendly } from '@/common/utils/date.js'
	
	// 日期范围选择
	const currentDateRange = ref('week')
	const dateRanges = [
		{ label: '今日', value: 'today' },
		{ label: '本周', value: 'week' },
		{ label: '本月', value: 'month' },
		{ label: '全部', value: 'all' }
	]
	
	// 类型筛选
	const typeIndex = ref(0)
	const typeOptions = [
		{ label: '所有类型', value: 'all' },
		{ label: '空腹', value: 'beforeBreakfast' },
		{ label: '早餐后', value: 'afterBreakfast' },
		{ label: '午餐前', value: 'beforeLunch' },
		{ label: '午餐后', value: 'afterLunch' },
		{ label: '晚餐前', value: 'beforeDinner' },
		{ label: '晚餐后', value: 'afterDinner' },
		{ label: '睡前', value: 'beforeSleep' },
		{ label: '随机', value: 'random' }
	]
	
	// 血糖记录列表
	const records = ref([])
	
	// 排序方式：true为降序（最新优先），false为升序（最早优先）
	const sortDesc = ref(true)
	
	// 血糖检测提醒
	const bloodSugarReminders = ref([])
	
	// 统计数据
	const statistics = reactive({
		average: '0.0',
		max: '0.0',
		min: '0.0',
		count: 0
	})
	
	// 筛选后的记录
	const filteredRecords = computed(() => {
		// 确保records.value是数组
		if (!Array.isArray(records.value)) {
			console.error('records.value不是数组:', records.value)
			return []
		}
		
		// 日期筛选
		let filtered = [...records.value]
		const now = new Date()
		let startDate = null
		
		switch (currentDateRange.value) {
			case 'today':
				// 今天
				startDate = new Date().toISOString().split('T')[0]
				filtered = filtered.filter(record => record.date === startDate)
				break
				
			case 'week':
				// 过去7天
				startDate = new Date(now - 7 * 24 * 60 * 60 * 1000).toISOString().split('T')[0]
				filtered = filtered.filter(record => new Date(record.date) >= new Date(startDate))
				break
				
			case 'month':
				// 过去30天
				startDate = new Date(now - 30 * 24 * 60 * 60 * 1000).toISOString().split('T')[0]
				filtered = filtered.filter(record => new Date(record.date) >= new Date(startDate))
				break
				
			// 全部无需过滤
		}
		
		// 类型筛选
		const selectedType = typeOptions[typeIndex.value].value
		if (selectedType !== 'all') {
			filtered = filtered.filter(record => record.type === selectedType)
		}
		
		// 排序
		filtered.sort((a, b) => {
			const dateA = new Date(`${a.date} ${a.time}`)
			const dateB = new Date(`${b.date} ${b.time}`)
			return sortDesc.value ? dateB - dateA : dateA - dateB
		})
		
		return filtered
	})
	
	// 按日期分组的记录
	const recordGroups = computed(() => {
		// 确保filteredRecords.value是数组
		if (!Array.isArray(filteredRecords.value)) {
			console.error('filteredRecords.value不是数组:', filteredRecords.value)
			return []
		}
		
		const groups = []
		const dateMap = {}
		
		// 按日期分组
		filteredRecords.value.forEach(record => {
			if (!dateMap[record.date]) {
				dateMap[record.date] = []
			}
			dateMap[record.date].push(record)
		})
		
		// 将分组转为数组并排序
		Object.keys(dateMap).sort((a, b) => sortDesc.value ? new Date(b) - new Date(a) : new Date(a) - new Date(b)).forEach(date => {
			groups.push({
				date,
				records: dateMap[date]
			})
		})
		
		return groups
	})
	
	// 加载血糖记录
	const loadRecords = async () => {
		uni.showLoading({
			title: '加载中...'
		})
		
		try {
			const res = await getRecords()
			if (res.code === 0) {
				records.value = res.data
			}
		} catch (e) {
			console.error('加载记录失败:', e)
			uni.showToast({
				title: '加载记录失败',
				icon: 'none'
			})
		} finally {
			uni.hideLoading()
		}
	}
	
	// 加载统计数据
	const loadStatistics = async () => {
		try {
			const params = {}
			
			// 根据筛选条件设置参数
			if (currentDateRange.value === 'today') {
				params.date = new Date().toISOString().split('T')[0]
			} else if (currentDateRange.value === 'week') {
				const now = new Date()
				params.startDate = new Date(now - 7 * 24 * 60 * 60 * 1000).toISOString().split('T')[0]
				params.endDate = now.toISOString().split('T')[0]
			} else if (currentDateRange.value === 'month') {
				const now = new Date()
				params.startDate = new Date(now - 30 * 24 * 60 * 60 * 1000).toISOString().split('T')[0]
				params.endDate = now.toISOString().split('T')[0]
			}
			
			const selectedType = typeOptions[typeIndex.value].value
			if (selectedType !== 'all') {
				params.type = selectedType
			}
			
			const res = await getStatistics(params)
			if (res.code === 0) {
				statistics.average = res.data.average.toFixed(1)
				statistics.max = res.data.max.toFixed(1)
				statistics.min = res.data.min.toFixed(1)
				statistics.count = res.data.count
			}
		} catch (e) {
			console.error('加载统计数据失败:', e)
		}
	}
	
	// 加载血糖检测提醒
	const loadReminders = async () => {
		try {
			const res = await getReminders()
			if (res.code === 0) {
				// 筛选出血糖检测相关的提醒
				bloodSugarReminders.value = res.data.filter(item => item.type === 'bloodSugar')
			}
		} catch (e) {
			console.error('加载提醒失败:', e)
		}
	}
	
	// 切换日期范围
	const changeDateRange = (range) => {
		currentDateRange.value = range
		loadStatistics()
	}
	
	// 切换类型筛选
	const typeChange = (e) => {
		typeIndex.value = e.detail.value
		loadStatistics()
	}
	
	// 切换排序顺序
	const toggleSortOrder = () => {
		sortDesc.value = !sortDesc.value
	}
	
	// 获取血糖值对应的CSS类名
	const getValueClass = (value) => {
		const val = parseFloat(value)
		if (isNaN(val)) return ''
		
		if (val < 3.9) return 'value-low'
		if (val > 6.1) return 'value-high'
		return 'value-normal'
	}
	
	// 获取血糖状态文本
	const getStatusText = (value) => {
		const val = parseFloat(value)
		if (val < 3.9) return '偏低'
		if (val > 6.1) return '偏高'
		return '正常'
	}
	
	// 获取血糖状态对应的CSS类名
	const getStatusClass = (value) => {
		const val = parseFloat(value)
		if (val < 3.9) return 'status-low'
		if (val > 6.1) return 'status-high'
		return 'status-normal'
	}
	
	// 获取时段类型文本
	const getTimeTypeText = (type) => {
		const typeMap = {
			'beforeBreakfast': '空腹',
			'afterBreakfast': '早餐后',
			'beforeLunch': '午餐前',
			'afterLunch': '午餐后',
			'beforeDinner': '晚餐前',
			'afterDinner': '晚餐后',
			'beforeSleep': '睡前',
			'random': '随机'
		}
		return typeMap[type] || type
	}
	
	// 格式化日期显示
	const formatDate = (dateStr) => {
		return formatDateFriendly(dateStr)
	}
	
	// 添加记录
	const addRecord = () => {
		uni.navigateTo({
			url: '/pages/record/add'
		})
	}
	
	// 查看记录详情
	const viewRecord = (record) => {
		uni.navigateTo({
			url: `/pages/record/detail?id=${record.id}`
		})
	}
	
	// 显示操作菜单
	const showActions = (record) => {
		uni.showActionSheet({
			itemList: ['查看详情', '编辑', '删除'],
			success: (res) => {
				switch (res.tapIndex) {
					case 0:
						viewRecord(record)
						break
					case 1:
						uni.navigateTo({
							url: `/pages/record/edit?id=${record.id}`
						})
						break
					case 2:
						confirmDelete(record)
						break
				}
			}
		})
	}
	
	// 确认删除
	const confirmDelete = (record) => {
		uni.showModal({
			title: '确认删除',
			content: '确定要删除这条血糖记录吗？',
			success: async (res) => {
				if (res.confirm) {
					try {
						const result = await deleteRecord(record.id)
						if (result.code === 0) {
							uni.showToast({
								title: '删除成功',
								icon: 'success'
							})
							loadRecords()
							loadStatistics()
						} else {
							throw new Error(result.message || '删除失败')
						}
					} catch (e) {
						console.error('删除记录失败:', e)
						uni.showToast({
							title: '删除失败',
							icon: 'none'
						})
					}
				}
			}
		})
	}
	
	// 跳转到提醒管理
	const goToReminders = () => {
		uni.navigateTo({
			url: '/pages/reminder/index'
		})
	}
	
	// 添加检测提醒
	const addReminder = () => {
		uni.navigateTo({
			url: '/pages/reminder/add?type=bloodSugar'
		})
	}
	
	// 切换提醒状态
	const toggleReminder = async (id, event) => {
		const active = event.detail.value
		
		try {
			const res = await toggleReminderStatus(id, active)
			if (res.code === 0) {
				uni.showToast({
					title: active ? '提醒已启用' : '提醒已禁用',
					icon: 'success'
				})
				
				// 更新本地状态
				const index = bloodSugarReminders.value.findIndex(item => item.id === id)
				if (index !== -1) {
					bloodSugarReminders.value[index].active = active
				}
			} else {
				throw new Error(res.message || '操作失败')
			}
		} catch (e) {
			console.error('切换提醒状态失败:', e)
			uni.showToast({
				title: '操作失败',
				icon: 'none'
			})
		}
	}
	
	// 页面加载完成
	onMounted(() => {
		loadRecords()
		loadStatistics()
		loadReminders()
	})
	
	// 每次页面显示时刷新数据
	onShow(() => {
		loadRecords()
		loadReminders()
	})
</script>

<style lang="scss">
	.blood-record-container {
		padding: 20rpx;
		background-color: #f5f7fa;
		min-height: 100vh;
		
		.header {
			display: flex;
			justify-content: space-between;
			align-items: center;
			margin-bottom: 20rpx;
			
			.title {
				font-size: 36rpx;
				font-weight: bold;
				color: #333;
			}
			
			.add-btn {
				background-color: #8cc9a1;
				color: #fff;
				font-size: 28rpx;
				padding: 10rpx 30rpx;
				border-radius: 30rpx;
				line-height: 1.5;
			}
		}
		
		.filter-section {
			background-color: #fff;
			border-radius: 16rpx;
			padding: 20rpx;
			margin-bottom: 20rpx;
			box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.05);
			
			.date-filter {
				display: flex;
				justify-content: space-between;
				margin-bottom: 20rpx;
				
				.filter-item {
					flex: 1;
					text-align: center;
					padding: 12rpx 0;
					font-size: 28rpx;
					color: #666;
					border-radius: 30rpx;
					
					&.active {
						background-color: #8cc9a1;
						color: #fff;
					}
				}
			}
			
			.type-filter {
				.type-selector {
					background-color: #f0f2f5;
					padding: 16rpx 20rpx;
					border-radius: 10rpx;
					display: flex;
					justify-content: space-between;
					align-items: center;
					font-size: 28rpx;
					color: #333;
					
					.arrow-down {
						font-size: 24rpx;
						color: #999;
					}
				}
			}
		}
		
		.stats-card {
			background-color: #fff;
			border-radius: 16rpx;
			padding: 20rpx;
			margin-bottom: 20rpx;
			box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.05);
			display: flex;
			justify-content: space-between;
			
			.stats-item {
				text-align: center;
				
				.stats-value {
					display: block;
					font-size: 32rpx;
					font-weight: bold;
					color: #333;
					margin-bottom: 8rpx;
					
					&.value-high {
						color: #ff6b6b;
					}
					
					&.value-normal {
						color: #8cc9a1;
					}
					
					&.value-low {
						color: #5b8def;
					}
				}
				
				.stats-label {
					font-size: 24rpx;
					color: #999;
				}
			}
		}
		
		.record-list {
			background-color: #fff;
			border-radius: 16rpx;
			padding: 20rpx;
			margin-bottom: 20rpx;
			box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.05);
			
			.list-header {
				display: flex;
				justify-content: space-between;
				align-items: center;
				margin-bottom: 20rpx;
				padding-bottom: 15rpx;
				border-bottom: 1px solid #f0f0f0;
				
				.list-title {
					font-size: 30rpx;
					font-weight: bold;
					color: #333;
				}
				
				.sort-btn {
					font-size: 26rpx;
					color: #666;
					display: flex;
					align-items: center;
					
					.sort-icon {
						margin-left: 6rpx;
					}
				}
			}
			
			.empty-tip {
				text-align: center;
				padding: 40rpx 0;
				color: #999;
				font-size: 28rpx;
			}
			
			.record-group {
				margin-bottom: 30rpx;
				
				.group-date {
					font-size: 26rpx;
					color: #999;
					margin-bottom: 15rpx;
				}
				
				.record-item {
					display: flex;
					justify-content: space-between;
					align-items: center;
					padding: 20rpx;
					margin-bottom: 15rpx;
					background-color: #f9f9f9;
					border-radius: 12rpx;
					
					.record-time-type {
						.time {
							font-size: 28rpx;
							color: #333;
							display: block;
							margin-bottom: 6rpx;
						}
						
						.type-label {
							font-size: 24rpx;
							color: #999;
							background-color: #f0f0f0;
							padding: 4rpx 12rpx;
							border-radius: 20rpx;
						}
					}
					
					.record-value-container {
						.value {
							font-size: 36rpx;
							font-weight: bold;
							color: #333;
							
							&.value-high {
								color: #ff6b6b;
							}
							
							&.value-normal {
								color: #8cc9a1;
							}
							
							&.value-low {
								color: #5b8def;
							}
						}
						
						.unit {
							font-size: 24rpx;
							color: #999;
							margin-left: 4rpx;
						}
					}
					
					.record-status {
						font-size: 24rpx;
						color: #fff;
						padding: 6rpx 16rpx;
						border-radius: 20rpx;
						
						&.status-high {
							background-color: #ff6b6b;
						}
						
						&.status-normal {
							background-color: #8cc9a1;
						}
						
						&.status-low {
							background-color: #5b8def;
						}
					}
				}
			}
		}
		
		.reminder-card {
			background-color: #fff;
			border-radius: 16rpx;
			padding: 20rpx;
			box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.05);
			
			.card-header {
				display: flex;
				justify-content: space-between;
				align-items: center;
				margin-bottom: 20rpx;
				
				.card-title {
					font-size: 30rpx;
					font-weight: bold;
					color: #333;
				}
				
				.view-all {
					font-size: 26rpx;
					color: #8cc9a1;
				}
			}
			
			.reminder-list {
				margin-bottom: 20rpx;
				
				.empty-tip {
					text-align: center;
					padding: 40rpx 0;
					color: #999;
					font-size: 28rpx;
				}
				
				.reminder-item {
					display: flex;
					justify-content: space-between;
					align-items: center;
					padding: 20rpx 0;
					border-bottom: 1px solid #f0f0f0;
					
					&:last-child {
						border-bottom: none;
					}
					
					.reminder-info {
						flex: 1;
						
						.reminder-title {
							font-size: 28rpx;
							color: #333;
							margin-bottom: 6rpx;
						}
						
						.reminder-desc {
							font-size: 24rpx;
							color: #999;
						}
					}
					
					.reminder-time {
						font-size: 28rpx;
						color: #8cc9a1;
						font-weight: bold;
						margin-right: 20rpx;
					}
				}
			}
			
			.add-reminder-btn {
				width: 100%;
				height: 80rpx;
				line-height: 80rpx;
				text-align: center;
				background-color: #8cc9a1;
				color: #fff;
				font-size: 28rpx;
				border-radius: 40rpx;
			}
		}
	}
</style> 